package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
public class BlackListFilter implements GlobalFilter, Ordered {
    @Autowired
    private IpFlushFirewall flushFirewall;
    // 模拟黑名单（实际可以去数据库或者redis中查询）
    private static List<String> blackList = new ArrayList<>();
    // 白名单
    private static List<String> whiteList = new ArrayList<>();

    static {
        // 黑名单
        blackList.add("0:0:0:0:0:0:0:1");  // 模拟本机地址
        // 白名单 使用正则表达式
        whiteList.add("/api/user/.*");// 用户模块不拦截
        whiteList.add("/api/code/create/.*");// 发送邮件
    }

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        // 拿着clientIp去黑名单中查询，存在的话就决绝访问
        // IP 防刷
        if (blackList.contains(clientIp) || flushFirewall.isIpLimited(clientIp)) {
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>IP:" + clientIp + " 在黑名单中，将被拒绝访问！");
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        // 登录拦截
        String url = request.getPath().toString();
        log.info("=====>请求地址：" + url);
        if (!isLoginFilter(url) && getCookies(request) == null) {
            log.info("=====>你没权限访问该资源：" + url);
            return fallBack("/static/login.html", exchange);
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    // 是否登录拦截
    public boolean isLoginFilter(String content) {
        for (String pattern : whiteList) {
            boolean isMatch = Pattern.matches(pattern, content);
            if (isMatch) {
                log.info("请求路径命中：(" + pattern + ")==>(" + content + ")");
                return true;
            }
        }

        return false;
    }

    /**
     * 失败返回message提示用户
     */
    private Mono<Void> fallBack(String url, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", url);
        return exchange.getResponse().setComplete();
    }

    /**
     * 获取登录cookie信息
     */
    public String getCookies(ServerHttpRequest request) {
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (cookies != null) {
            for (String key : cookies.keySet()) {
                if ("token".equals(key)) {
                    List<HttpCookie> responseCookies = cookies.get(key);
                    if (responseCookies.size() > 0) {
                        HttpCookie httpCookie = responseCookies.get(0);
                        log.info("登录cookie信息：" + httpCookie);
                        return httpCookie.getValue();
                    }
                }
            }
        }

        return null;
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
